#include "muduo/proto/dispatcher.h"
#include "muduo/proto/codec.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/base/CountDownLatch.h"

#include "request.pb.h"

#include <iostream>
#include <unistd.h>

class Client
{
public:
    typedef std::shared_ptr<google::protobuf::Message> MessagePtr;
    typedef std::shared_ptr<castle::TranslateResponse> TranslateResponsePtr;
    typedef std::shared_ptr<castle::AddResponse> AddResponsePtr;
    
    Client(const std::string sip,int sport)
    :_latch(1),
    _dispatcher(std::bind(&Client::onUnknownMessage, this, 
    std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
    _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher,
    std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
    _client(_loopthread.startLoop(),muduo::net::InetAddress(sip,sport),"Client")
    {
        //注册业务处理函数
        _dispatcher.registerMessageCallback<castle::TranslateResponse>(std::bind(&Client::onTranslate,this,
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _dispatcher.registerMessageCallback<castle::AddResponse>(std::bind(&Client::onAdd,this,
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, 
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        
        _client.setConnectionCallback(std::bind(&Client::onConnection, this, std::placeholders::_1));
    }

    //连接服务器，需要阻塞等待连接建立之后再返回
    void connect()
    {
        _client.connect();
        _latch.wait();
    }


    void translate(const std::string& msg)
    {
        castle::TranslateRequest req;
        req.set_msg(msg);
        send(&req);
    }

    void add(int num1,int num2)
    {
        castle::AddRquest req;
        req.set_num1(num1);
        req.set_num2(num2);
        send(&req);
    }

    

private:
    bool send(const google::protobuf::Message *msg)
    {
        //连接状态正常再发送
        if(_conn->connected())
        {
            _codec.send(_conn,*msg);
            return true;
        }
        return false;
    }

    void onTranslate(const muduo::net::TcpConnectionPtr& conn,
                        const TranslateResponsePtr& message,
                        muduo::Timestamp)
    {
        std::cout << "翻译结果: " << message->msg() << std::endl;
    }

    void onAdd(const muduo::net::TcpConnectionPtr& conn,
                        const AddResponsePtr& message,
                        muduo::Timestamp)
    {
        std::cout << "加法结果: " << message->result() << std::endl;
    }

    void onUnknownMessage(const muduo::net::TcpConnectionPtr& conn,
                        const MessagePtr& message,
                        muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }

    // 新连接建立成功时的回调函数，需要唤醒上边的阻塞
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
    	std::cout << "onConnection ...." << std::endl;
        // 新连接建立成功时的回调函数
        if(conn->connected())
        {
            //唤醒主线程的阻塞
            _conn=conn;
            _latch.countDown(); //唤醒主线程
    	    std::cout << "conn->connected() ...." << std::endl;
        }
        else
        {
            _conn.reset();  
    	    std::cout << "_conn.reset(); ...." << std::endl;
        }
    }

private:
    muduo::CountDownLatch _latch;//实现同步
    muduo::net::EventLoopThread _loopthread;//异步循环处理线程
    muduo::net::TcpClient _client;//客户端
    muduo::net::TcpConnectionPtr _conn;//客户端对应的连接
    ProtobufDispatcher _dispatcher;//请求分发器
    ProtobufCodec _codec;//协议处理器
};



int main()
{
    Client client("127.0.0.1",8005);
    client.connect();

    client.translate("hello");
    client.add(2,4);

    sleep(1);    
    return 0;
}
